#!/usr/bin/python
# -*- coding: utf-8 -*-



from django.http import HttpResponseRedirect
from django.http import HttpResponse
from django.utils import simplejson



def json_wrapper_list(request, data_list,varname="data"):
    message ={varname:data_list}
    return HttpResponse(simplejson.dumps(message), mimetype='application/json')

def json_wrapper(request, data,varname="data"):
    try:
        message ={varname:data.encode("utf-8")}
    except:
        message ={varname:str(data)}
    return HttpResponse(simplejson.dumps(message), mimetype='application/json')


def import_class(class_string):
    module_name, _, class_name = class_string.rpartition('.')
    if module_name == '':
        raise ValueError('Class name must contain module part.')
    return getattr(
        __import__(module_name, globals(), locals(), [class_name], -1),
        class_name)



def default_toogle_function(current_var,varname,value):
    
    #Функция булиновых переменных. 
    if varname=="MITM_STATUS":
        # Включаем или выключаем mitm
        from sockets.tasks import SocketServerStart
        SocketServerStart.delay(0)
        SocketServerStart.AsyncResult()
        print SocketServerStart.get()
        



def setvar(request,varname="version",value="0.1"):
    from models import Var
    all_vars=Var.objects.filter(name=varname)
    if len(all_vars)==1:
        current_var=all_vars[0]
        # Если переменная Boolean
        if current_var.type=="B":
            # Пробуем запустить функцию из поля advanced
            if "task:" in current_var.advanced:
                default_toogle_function(current_var,varname,value)
            else:
                current_var.value=value
                current_var.save()

            return json_wrapper(request,current_var.get_value(),varname)
        else:
            current_var.name=varname
            current_var.value=value
            current_var.save()
            return json_wrapper(request,current_var.get_value(),varname)
    else:
        newvar=Var(name=varname,value=value)
        newvar.save()
        return json_wrapper(request,newvar.get_value(),varname)




def getvar(request,varname="version"):
    from models import Var

    all_vars=Var.objects.filter(name=varname)
    
    if len(all_vars)==1:
        if varname=="WEB_SOCKET_PORT":
            
            from models import Var
            from sockets.models import Socket
            w_socket=all_vars[0].get_value()
            #print dir(w_socket.getSocket())
            print w_socket.getSocket()
            #web_socket=Socket.objects.get(pk=index_socket)
            #print web_socket
            #print web_socket, type(web_socket)#, web_socket.getStatus()
        return json_wrapper(request,all_vars[0].get_value(),varname)
    else:
        from models import VarGroup
        is_group=VarGroup.objects.filter(name=varname)
        if len(is_group)==1:
            return json_wrapper_list(request,is_group[0].get_value(),varname)
        else:
            return json_wrapper(request,"error 404",varname)
